<template>
    <div class="app-container">
        <!-- 查询条件表单 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="文件名" prop="originalName">
                <el-input v-model="queryParams.originalName" placeholder="请输入文件名" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="文件日期">
                <el-date-picker v-model="createTimeStr" type="daterange" range-separator="至" start-placeholder="开始日期"
                    value-format="yyyy-MM-dd" end-placeholder="结束日期" @change="dateChange">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格上方工具栏 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['fileshare:index:add']" v-if="!isSupplierMode">新增文件</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-s-management" size="mini" @click="handleAddReceiver"
                    v-hasPermi="['system:role:add']">新增收件人</el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-share" size="mini" @click="handleBatchSend"
                    v-hasPermi="['fileshare:index:sendbatch']" v-if="!isSupplierMode">批量发送</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getFileList"></right-toolbar>
        </el-row>

        <!-- 表格 -->
        <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" height="500"
            style="width: 100%;" ref="table">
            <template slot="empty">
                <p v-if="isSupplierMode">暂无文件分享给您。</p>
                <p v-else>暂无文件数据。</p>
            </template>
            <el-table-column type="selection" width="80" fixed="left" />
            <el-table-column label="序号" type="index" width="80" />
            <el-table-column label="文件" prop="originalName">
                <template slot-scope="scope">
                    <div style="line-height: 20px;">
                        {{ scope.row.originalName }}
                        <el-image style="width: 20px; height: 20px" :src="getDisplayImageRs(scope.row.originalName)"
                            fit="scale-down" />
                        <el-tag v-if="scope.row.isShare" type="success" size="mini" effect="plain">来自分享</el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column v-if="!isSupplierMode" label="哈希" prop="hash" />
            <el-table-column v-if="!isSupplierMode" label="分享供应商" prop="shareUserIds">
                <template slot-scope="scope">
                    <el-tag v-for="item in getUserNames(scope.row.shareUserIds)" :key="item" type="" effect="plain"
                        size="mini">
                        {{ item }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column :label="isSupplierMode?'分享人':'上传人'" prop="createUser" />
            <el-table-column label="上传时间" prop="createTime" />
            <el-table-column label="更新人" prop="updateUser" />
            <el-table-column label="更新时间" prop="updateTime" />
            <el-table-column label="操作" fixed="right" width="300">
                <template slot-scope="scope">
                    <el-button size="small" plain type="success" icon="el-icon-share" @click="handleRowSend(scope.row)"
                        v-if="!isSupplierMode" v-hasPermi="['fileshare:index:send']"
                        style="padding: 5px;">发送</el-button>
                    <el-button size="small" plain type="primary" icon="el-icon-notebook-2"
                        @click="handleRowDetail(scope.row)" v-if="!isSupplierMode"
                        v-hasPermi="['fileshare:index:detail']" style="padding: 5px;">详情</el-button>
                    <el-button size="small" plain type="danger" icon="el-icon-delete"
                        @click="handleRowDelete(scope.row)" v-if="!isSupplierMode && !scope.row.isShare"
                        v-hasPermi="['fileshare:index:delete']" style="padding: 5px;">删除</el-button>
                    <el-button size="small" plain type="primary" icon="el-icon-bottom"
                        @click="handleRowDownload(scope.row)" style="padding: 5px;" v-if="isSupplierMode"
                        :disabled="downloadDisable">{{ downloadText }}</el-button>
                    <el-dropdown v-if="!isSupplierMode && !scope.row.isShare" size="mini"
                        @command="(command) => handleMoreRowCommand(command, scope.row)">
                        <el-button size="small" plain type="text" icon="el-icon-d-arrow-right">更多</el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleRowShare" icon="el-icon-share">分享</el-dropdown-item>
                            <el-dropdown-item command="handleRowCancelShare"
                                icon="el-icon-close-notification">取消分享</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit"
            @pagination="getFileList" />
        <addtion-dialog :formData="addtionDialogData" v-if="addtionDialogVisible" :dialogVisible="addtionDialogVisible"
            @close="onAddtionDialogClose" :loginUserId="userMeta.systemUserId">
        </addtion-dialog>
        <send-dialog :sendList="sendDataList" v-if="sendDialogVisible" :visible="sendDialogVisible"
            @close="onSendDialogClose">
        </send-dialog>
        <view-detail-dialog v-if="viewDetailDialogVisible" :visible="viewDetailDialogVisible" :data="currentFile"
            @close="onviewDetailDialogClose">
        </view-detail-dialog>
        <share-dialog v-if="shareDialogVisible" :dialogVisible="shareDialogVisible" :file="currentFile2" :add="isAdd"
            @close="onShareDialogClose">
        </share-dialog>
    </div>
</template>

<script>
import request from '@/utils/request'
import addtionDialog from './components/addtionDialog.vue'
import sendDialog from './components/sendDialog.vue'
import viewDetailDialog from './components/viewDetailDialog.vue'
import shareDialog from './components/shareDialog.vue'

export default {
    name: "shareIndex"
    , components: {
        addtionDialog
        , sendDialog
        , viewDetailDialog
        , shareDialog
    }
    , data() {
        return {
            queryParams: {
                page: 1
                , limit: 10
                , originalName: ''
                , createTime: ''
                , start: ''
                , end: ''
            }
            , userMeta: {}
            , isSupplierMode: false
            , createTimeStr: ''
            , total: 0
            , showSearch: true
            , loading: false
            , tableData: []
            , selects: []
            , addtionDialogVisible: false
            , addtionDialogData: {}
            , sendDialogVisible: false
            , sendDataList: []
            , viewDetailDialogVisible: false
            , shareDialogVisible:false
            , currentFile: {}
            , currentFile2:{}
            ,isAdd:true
            , imageMap: {
                "png": require("@/assets/images/PNG.png")
                , "jpg": require("@/assets/images/JPG.png")
                , "jpeg": require("@/assets/images/JPG.png")
                , "gif": require("@/assets/images/GIF.png")
                , "bmp": require("@/assets/images/BMP.png")
                , "cad": require("@/assets/images/CAD.png")
                , "pdf": require("@/assets/images/PDF.png")
                , "default": require("@/assets/images/DOC.png")
            }
            , downloadDisable: false
            , downloadText: "下载"
            , userDatas:[]
        }
    }
    , methods: {
        getFileList() {
            this.loading = true;
            request({
                url: '/file-share/list'
                , method: 'get'
                , params: this.queryParams
            }).then(res => {
                if (res.code === 200) {
                    this.tableData = res.data.list
                    this.total = res.data.total
                } else {
                    this.$message.error(res.msg)
                }
                this.loading = false;
            })
                .catch(err => {
                    console.log(err)
                    this.$modal.msgError(err)
                    this.loading = false;
                })
        }
        , getMeta() {
            return request({
                url: '/file-share/meta'
                , method: 'get'
            })
        }
        
        , init() {
            window.addEventListener("resize", this.handleResize);
            this.getMeta()
            .then(res => {
                if (res && res.code === 200) {
                    this.userMeta = res.data;
                }
            })
            .finally(() => {
                if(!this.isSupplierMode){
                    this.getSelectUserList();
                    this.getSupplierList();
                }else{
                    this.getFileList();
                }
            })
        }
        , handleResize() {
            this.$nextTick(() => {
                this.$refs.table.doLayout();
            });
        }
        , handleQuery() {
            this.getFileList();
        }
        , resetQuery() {
            this.queryParams = {
                page: 1
                , limit: 10
                , originalName: ''
                , createTime: ''
                , start: ''
                , end: ''
            }
            this.createTimeStr = '';
            this.getFileList();
        }
        , handleAdd() {
            this.addtionDialogData = {};
            this.addtionDialogVisible = true;
        }
        , handleBatchSend() {
            if (this.sendDataList.length === 0) {
                this.$modal.msgWarning("请选择需要发送的文件。");
                return;
            }
            if (this.sendDataList.length > 10) {
                this.$modal.alertWarning("一次最多可发送10个文件。");
                return;
            }
            this.sendDialogVisible = true;
        }
        , handleSelectionChange(selects) {
            this.selects = [];
            this.sendDataList = [];
            if (selects && selects.length !== 0) {
                this.selects = selects.map(sl => sl.assetNo);
                this.sendDataList = selects.map(sl => sl);
            }
        }
        , handleRowSend(row) {
            this.sendDataList = [];
            this.sendDataList.push(row);
            this.sendDialogVisible = true;
        }
        , handleRowEdit(row) {
            this.addtionDialogData = row;
            this.addtionDialogVisible = true;
        }
        , handleRowDelete(row) {
            this.$modal.confirm('是否确认删除文件"' + row.originalName + '?').then(function () {
                return request({
                    url: '/file-share/delete/' + row.id
                    , method: 'delete'
                })
            }).then((res) => {
                if (res && res.code === 200) {
                    this.getFileList();
                    this.$modal.msgSuccess("删除成功。");
                } else {
                    this.$modal.msgError(res.msg);
                }
            }).catch((e) => {
                console.log(e);
            });
        }
        , onAddtionDialogClose(isDataModify) {
            this.addtionDialogVisible = false;
            this.addtionDialogData = {};
            if (isDataModify)
                this.getFileList();
        }
        , onSendDialogClose(isRefresh) {
            this.sendDialogVisible = false;
            this.getFileList();
            this.sendDataList = [];
            this.selects = [];
        }
        , onviewDetailDialogClose() {
            this.viewDetailDialogVisible = false;
            this.currentFile = {};
        }
        , onShareDialogClose(){
            this.shareDialogVisible = false;
            this.currentFile2 = {};
            this.isAdd = true;
            this.getFileList();
        }
        , dateChange(dates) {
            this.queryParams.start = dates[0];
            this.queryParams.end = dates[1];

        }
        , getDisplayImageRs(fileName) {
            let ar = fileName.split(".");
            let suffix = ar[ar.length - 1].toLowerCase();
            let r = this.imageMap[suffix];
            if (r) {
                return r;
            }
            return this.imageMap["default"];
        }
        , handleRowDetail(row) {
            // console.log(row);
            this.currentFile = row;
            this.viewDetailDialogVisible = true;
        }
        // 触发浏览器下载row中url字段指定的文件
        , handleRowDownload(row) {
            this.downloadDisable = true;
            request({
                url: '/file-share/receiver/download-log'
                , method: 'post'
                , data: row
            })
            .then(res => {
                if (res && res.code === 200) {
                    let url = `/common/download-share-file/${row.id}`;
                    return request({
                        url: url
                       , method: 'get'
                       , responseType: 'blob'
                    })
                } else {
                    throw new Error(res.msg);
                }
            })
            .then(response => {
                if (response.type === 'application/json') {
                    throw new Error("下载失败，无法读取文件流，物理文件不存在，请检查文件服务或数据库是否修改。");
                }
                const fileName = row.originalName;
                const blob = new Blob([response], { type: 'application/octet-stream' });
                const downloadUrl = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = downloadUrl;
                link.setAttribute('download', fileName);
                document.body.appendChild(link);
                link.click();
                link.remove();
                window.URL.revokeObjectURL(downloadUrl);
            })
            .catch(err => this.$modal.msgError(err))
            .finally(() => {
                setTimeout(() => {
                    this.downloadDisable = false;
                }, 3000);
            });
        }
        ,handleMoreRowCommand(command,row){
            this.currentFile2 = row;
            switch (command) {
                case 'handleRowShare':
                    this.isAdd = true;
                    this.shareDialogVisible = true;
                    break;
                case 'handleRowCancelShare':
                    this.isAdd = false;
                    this.shareDialogVisible = true;
                    break;
                default:
                    break;
            }
        }
        , getSelectUserList() {
            request({
                url: '/system/user/list'
                , method: 'get'
                , params: { pageNum: 1, pageSize: 99999 }
            }).then(res => {
                this.userDatas = [];
                if (res && res.code === 200) {
                    this.userDatas = res.rows;
                }
                this.getFileList();
            })
            .catch(err => {
                console.log(err);
            })
        }
        ,getUserNames(ids){
            if(!this.userDatas||this.userDatas.length===0||!ids||ids.length===0){
                return ids;
            }
            let finds = [];
            ids = ids.split(';');
            for (let element of this.userDatas) {
                let fd = ids.findIndex(i => i === String(element.userId));
                if(fd>-1){
                    finds.push(element.userName);
                }
            }
            return finds;
        }
        ,getSupplierList() {
            this.loading = true;
            request({
                url: '/file-share/receiver/select-list'
                , method: 'get'
            }).then(res => {
                if (res.code === 200) {
                    localStorage.setItem('supplier-list', JSON.stringify(res.data));
                } else {
                    this.$message.error(res.msg)
                }
            })
            .catch(err => {
                console.log(err)
                this.$modal.msgError(err)
            })
            .finally(() => {
                this.loading = false;
            })
        }
    }
    , mounted() {
        this.init();
    }
    ,beforeDestroy() {
        // 组件销毁时移除事件监听
        window.removeEventListener("resize", this.handleResize);
    }
    , watch: {
        userMeta: {
            handler(newVal, oldVal) {
                if (newVal.isDeleted === false && newVal.isSupplier) {
                    this.isSupplierMode = true;
                    this.$modal.alert("您已绑定或认证为供应商用户，已将视图切换为供应商模式。");
                }
            }
            , deep: true
        }
    }
}

</script>

<style scoped></style>